// 与 From 和 Into 类似，TryFrom 和 TryInto 是用于类型转换的泛型特质。
// 与 From/Into 不同，TryFrom/TryInto 特质用于可能失败的转换，
// 因此返回 Result。

#[derive(Debug, PartialEq)]
struct EvenNumber(i32);

impl TryFrom<i32> for EvenNumber {
    type Error = ();

    fn try_from(value: i32) -> Result<Self, Self::Error> {
        if value % 2 == 0 {
            Ok(EvenNumber(value))
        } else {
            Err(())
        }
    }
}

#[test]
fn test_tryfrom_tryinto() {
    // TryFrom
    let result1 = EvenNumber::try_from(8);
    match result1 {
        Ok(en) => println!("{}", en.0),
        Err(_) => println!("不是偶数"),
    }
    let result1 = EvenNumber::try_from(5);
    match result1 {
        Ok(en) => println!("{}", en.0),
        Err(_) => println!("不是偶数"),
    }

    // assert_eq!(EvenNumber::try_from(8), Ok(EvenNumber(8)));
    // assert_eq!(EvenNumber::try_from(5), Err(()));

    // TryInto
    let result: Result<EvenNumber, ()> = 8i32.try_into();
    match result {
        Ok(en) => println!("{}", en.0),
        Err(_) => {}
    }
    // assert_eq!(result, Ok(EvenNumber(8)));
    let result: Result<EvenNumber, ()> = 5i32.try_into();
    assert_eq!(result, Err(()));
}